package com.example.tms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.tms.common.annotation.LogAction;
import com.example.tms.common.enums.Result;
import com.example.tms.entity.SystemLog;
import com.example.tms.service.SystemLogService;

@RestController
@RequestMapping("/syslogs")
public class SystemLogController {

    @Autowired
    private SystemLogService systemLogService;

    // 分页查询日志
    @LogAction(value = "查询日志")
    @GetMapping("")
    @PreAuthorize("hasRole('ADMIN')")    
    public Result<Page<SystemLog>> getLogs(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String level,
            @RequestParam(required = false) String userId) {

        QueryWrapper<SystemLog> wrapper = new QueryWrapper<>();
        if (level != null && !level.isEmpty()) {
            wrapper.eq("level", level);
        }
        if (userId != null && !userId.isEmpty()) {
            wrapper.eq("user_id", userId);
        }
        wrapper.orderByDesc("created_at");

        Page<SystemLog> page = new Page<>(pageNum, pageSize);
        return Result.success(systemLogService.page(page, wrapper));
    }

    // 根据ID查询日志详情
    @LogAction(value = "根据id查询日志")
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')") 
    public Result<SystemLog> getLogById(@PathVariable Integer id) {
        return Result.success(systemLogService.getById(id));
    }

    // 删除日志（逻辑删除）
    @LogAction(value = "删除日志", level = "WARN")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')") 
    public Result<Void> deleteLog(@PathVariable Integer id) {
        systemLogService.removeById(id);
        return Result.success();
    }

    // 清空日志（物理删除）
    @LogAction(value = "清空日志", level = "WARN")
    @DeleteMapping("")
    @PreAuthorize("hasRole('ADMIN')") 
    public Result<Void> clearLogs() {
        systemLogService.remove(new QueryWrapper<>());
        return Result.success();
    }
}
